/*
 * @Author: CPS
 * @Date: 2020-07-18 19:10:19
 * @Last Modified by:   CPS
 * @Last Modified time: 2020-08-05 16:37:08
 * @Projectname Electron-fileWatcher
 * @Filename index.js
 * 给予一个文件夹,读取其详细结构,返回对象
 */
'use strict'
const fs = require('fs');
const path = require('path');

const readDocx = require('./readDocx.js');
const getFolderSize = require('./getFolderSize.js');
const convertStructure = require('./addStructure.js');
const addElement = require('./addElement.js');


let getExtInfo = {
  docx: readDocx,
  doc: readDocx,
}

// addFolder 生成的格式
let tamplate = {
  dirname: '7月',
  path: 'D:\\CPS\\MyProject\\Electron-fileWatcher\\design\\resource\\2020年\\7月',
  lastModiTime: 0,
  files: [{
    type: '文件夹',
    name: '16948 （地球人）',
    path: 'D:\\CPS\\MyProject\\Electron-fileWatcher\\design\\resource\\2020年\\7月\\16948 （地球人）',
    size: '29.04MB'
  }, {
    type: '文件',
    ext: 'doc',
    name: 'test2 - 副本 - 副本 - 副本 - 副本',
    fullname: 'test2 - 副本 - 副本 - 副本 - 副本.doc',
    path: 'D:\\CPS\\MyProject\\Electron-fileWatcher\\design\\resource\\2020年\\7月\\test2 - 副本 - 副本 - 副本 - 副本.doc',
    size: '31.22MB',
    pages: 0,
    words: 0,
    lines: 0
  }],
}

function getFileSize(fileSize) {
  if (fileSize < 1024) {
    return fileSize + 'B';
  } else if (fileSize < (1024 * 1024)) {
    let temp = fileSize / 1024;
    temp = temp.toFixed(2);
    return temp + 'KB';
  } else if (fileSize < (1024 * 1024 * 1024)) {
    let temp = fileSize / (1024 * 1024);
    temp = temp.toFixed(2);
    return temp + 'MB';
  } else {
    let temp = fileSize / (1024 * 1024 * 1024);
    temp = temp.toFixed(2);
    return temp + 'GB';
  }
}

/**
 * 给以一个目录,读取该目录结构,并返回一个对象记录
 *
 * @param      {string}  [input='./']  The input
 * @return     {<type>}  { description_of_the_return_value }
 */
function readFolder(input = './') {
  try {
    //判断是否目录
    if (fs.lstatSync(input).isFile()) return

    //验证目录是否为空
    let dir = fs.readdirSync(input);
    if (dir.length == 0) return

    // console.log('当前目录：' + path.resolve(input))
    let info = {
      dirname: path.basename(path.resolve(input)),
      path: path.resolve(input),
      lastModiTime: 0,
      files: [],
    }

    // 遍历每个文件/文件夹
    dir.forEach((item) => {
      //读取基本信息
      let each = fs.lstatSync(path.resolve(input, item));

      if (each.isFile()) {
        //如果是文件
        //获取文件格式
        let ext = path.extname(item).toLowerCase()
        let extInfo = {
          type: '文件',
          ext: ext.replace('.', ''),
          name: path.basename(item, ext),
          fullname: item,
          path: path.resolve(input, item),
          size: getFileSize(each.size),
          pages: 0,
          words: 0,
          lines: 0,
        }

        //使用getExtInfo函数，获取文件的 页数 行数 字数 大小 信息
        if (getExtInfo.hasOwnProperty(extInfo.ext)) {
          Object.assign(extInfo, getExtInfo[extInfo.ext](extInfo.path))
        }

        // 合并结果
        info.files.push(extInfo)
      } else {
        info.files.push({
          type: '文件夹',
          name: path.basename(path.resolve(item)),
          path: path.resolve(input, item),
          size: getFolderSize(path.resolve(input, item)),
        })
      }
    })

    return info
  } catch (e) {
    console.log('readFolder.js 出错啦,请检查文件夹是否存在')
    console.log(e)
    return
  }

}

if (require.main === module) {
  let p = 'D:/CPS/MyProject/Electron-fileWatcher/design/resource/资料';
  let P = 'D:/CPS/MyProject/Electron-fileWatcher/design/resource/2020年/7月';
  let res = readFolder(P)

  console.log('结果：')
  console.log(res)

}

let run = {
  '读取目录到数据': readFolder,
  '转成数据成结构': convertStructure,
  '创建element元素': addElement,
}

module.exports = (tarPath, icon) => {
  if (!tarPath) return
  let f = fs.lstatSync(tarPath)
  if (!f || f.isFile()) return

  let folderData = run['读取目录到数据'](tarPath);
  let folderStructure = run['转成数据成结构'](folderData, icon);
  let newElement = run['创建element元素'](folderStructure);
  return newElement
}